package com.etalk.crm.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jordan
 */
public class PojoMapUtils {

    public static  <T> Map<String, Object> convert2Map(T t){
        Map<String, Object> result = new HashMap<String, Object>();
        Method[] methods = t.getClass().getMethods();
        try {
            for (Method method : methods) {
                Class<?>[] paramClass = method.getParameterTypes();
                // 如果方法带参数，则跳过
                if (paramClass.length > 0) {
                    continue;
                }
                String methodName = method.getName() ;
                if (methodName.startsWith("get")) {
                    Object value = method.invoke(t);
                    result.put(lowerFirstCase(methodName.replace("get","")), value);
                }
            }
        } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | SecurityException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将字符串的首字母转大写
     * @param str 需要转换的字符串
     * @return
     */
    private static String captureName(String str) {
        // 进行字母的ascii编码前移，效率要高于截取字符串进行转换的操作
        char[] cs=str.toCharArray();
        cs[0]-=32;
        return String.valueOf(cs);
    }

    public static String lowerFirstCase(String str){

        char[] chars = str.toCharArray();

        //首字母小写方法，大写会变成小写，如果小写首字母会消失
        chars[0] +=32;
        return String.valueOf(chars);

    }
}
